#!/bin/sh

#
# RedPorts Poudriere backend build creation script
#
# $Id: rpcreatebuild 645 2014-12-05 14:23:37Z mathieu.arnold@gmail.com $
#

# Requirements:
#   poudriere (ports-mgmt/poudriere-devel)
#   zfs

PORTSUSER=www
POUDRIERE=/poudriere
ZPOOL=zroot

if [ -z "$1" -o -z "$2" ]; then
    echo "Usage ${0##*/} version architecture [extra-suffix]"
    echo ""
    echo "Options:"
    echo "  version        FreeBSD Version (eg. 10, 8.2, 9-STABLE)"
    echo "  architecture   Machine architecture (i386, amd64)"
    echo "  extra-suffix   Name suffix (CLANG, GCC46)"
    echo ""
    exit 1
fi

VERSION=$1
ARCH=$2

if [ ! -z "$3" ]; then
    SUFFIX=-${3}
else
    SUFFIX=
fi

# Jails can't have a . in their names.
BUILD=`echo ${VERSION}-${ARCH}${SUFFIX}|sed -e 's/\./_/g'`

# 9-STABLE -> stable/9
# 10.0 -> 10.0-RELEASE
# 11 -> 11-CURRENT
if echo ${VERSION} | grep "-" > /dev/null ; then
    OPTIONS="-v stable/${VERSION%-STABLE} -m svn+https"
elif ! echo ${VERSION} | grep "\." > /dev/null ; then
    OPTIONS="-v ${VERSION} -m url=http://admin-http.nyi.freebsd.org/install/${ARCH}_${VERSION}"
else
    OPTIONS="-v ${VERSION}-RELEASE -m http"
fi

set -e

# Make sure www is allowed to do stuff to the ports trees
zfs allow -s @rppoudriere rollback,snapshot,rename,destroy,mount zroot/poudriere/ports
zfs allow -d -u www @rppoudriere zroot/poudriere/ports

/usr/local/bin/poudriere ports -c -p ${BUILD} -m svn+https -q 
chown -R ${PORTSUSER} ${POUDRIERE}/ports/${BUILD}
zfs snapshot ${ZPOOL}${POUDRIERE}/ports/${BUILD}@clean
/usr/local/bin/poudriere jail -c -j ${BUILD} -a ${ARCH} ${OPTIONS}

if [ -f "${POUDRIERE}/jails/${BUILD}/.svnrev.txt" ]
then
    tmp=`mktemp -u`
    echo `cat /usr/local/etc/poudriere.d/jails/${BUILD}/version`@`cat ${POUDRIERE}/jails/${BUILD}/.svnrev.txt`> $tmp
    mv $tmp /usr/local/etc/poudriere.d/jails/${BUILD}/version
fi

exit 0
